package com.jspgou.cms.action.store;

import static com.jspgou.cms.Constants.STORE_SYS;
import static com.jspgou.common.page.SimplePage.cpn;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jspgou.cms.entity.Category;
import com.jspgou.cms.entity.Role;
import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.entity.Store;
import com.jspgou.cms.entity.StoreExt;
import com.jspgou.cms.entity.StoreTxt;
import com.jspgou.cms.manager.CategoryMng;
import com.jspgou.cms.manager.OrderMng;
import com.jspgou.cms.manager.ProductMng;
import com.jspgou.cms.manager.RoleMng;
import com.jspgou.cms.manager.StoreExtMng;
import com.jspgou.cms.manager.StoreMng;
import com.jspgou.cms.web.CmsUtils;
import com.jspgou.cms.web.ShopFrontHelper;
import com.jspgou.cms.web.SiteUtils;
import com.jspgou.common.page.Pagination;
import com.jspgou.common.web.CookieUtils;
import com.jspgou.common.web.RequestUtils;
import com.jspgou.common.web.ResponseUtils;
import com.jspgou.common.web.session.SessionProvider;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.Global;
import com.jspgou.core.entity.Website;
import com.jspgou.core.web.WebErrors;
import com.jspgou.core.web.front.FrontHelper;
import com.octo.captcha.service.CaptchaService;
import com.octo.captcha.service.CaptchaServiceException;

@Controller
public class RegisterStoreAct {
	private static final Logger log = LoggerFactory.getLogger(RegisterStoreAct.class);
	
	/**
	 * 店铺中心页
	 */
	public static final String STORE_CENTER = "tpl.storeCenter";
	/**
	 * 店铺重新申请页
	 */
	public static final String STORE_AGAIN = "tpl.storeAgain";
	/**
	 * 店铺注册页
	 */
	public static final String STORE_REGISTRER = "tpl.storeRegister";
	/**
	 * 店铺注册协议页
	 */
	private static final String REGISTER_STORE_TREATY = "tpl.registerStoreTreaty";


	@RequestMapping(value = "/registerStore.jspx",method = RequestMethod.GET)
	public String registerInput(HttpServletRequest request,Integer pageNo, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		//用户没有登录，跳转到登录页
		if(member == null){
			return ShopFrontHelper.showLogin(request, model, web);
		}
		Store store=member.getStore();
		//用户店铺中心
		if(store!=null){
			if(!store.getExamine()){
				model.addAttribute("store", store);
				List<Category> categoryList=categoryMng.getList(web.getId());
				model.addAttribute("categoryList", categoryList);
				ShopFrontHelper.setCommonData(request, model, web);
				return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,STORE_AGAIN), request);
		    }
			Pagination pagination = productMng.getPage(web.getId(),null,store.getId(),
					null,null,null,false,null,null,null,
					null,null,null,null,cpn(pageNo), CookieUtils.getPageSize(request));
			Pagination paginationList = productMng.getPage(web.getId(),null,store.getId(),
					null,null,null,null,null,null,null,
					null,null,null,null,cpn(pageNo), CookieUtils.getPageSize(request));
            List<Object> o=orderMng.getStoreTotalOrder(store.getId());
            Long[] a=(Long[])o.get(0);
            BigDecimal[] b=(BigDecimal[]) o.get(1);
            model.addAttribute("a", a);
            model.addAttribute("b", b);
			model.addAttribute("pagination", pagination);
			model.addAttribute("paginationList", paginationList);
			model.addAttribute("store", store);
			ShopFrontHelper.setCommonData(request, model, web);
			ShopFrontHelper.frontPageData(request, model);
			return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,STORE_CENTER), request);
		}else{
			List<Category> categoryList=categoryMng.getList(web.getId());
			model.addAttribute("categoryList", categoryList);
			ShopFrontHelper.setCommonData(request, model, web);
			ShopFrontHelper.frontPageData(request, model);
			return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,STORE_REGISTRER), request);
		}
	}

	@RequestMapping(value = "/storeRegister.jspx",method = RequestMethod.POST)
	public String registerSubmit(Store bean, StoreExt ext,StoreTxt txt,Long categoryId,
			String checkcode, String nextUrl,HttpServletRequest request,
			HttpServletResponse response, ModelMap model) throws IOException {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		Global global=SiteUtils.getWeb(request).getGlobal();
		WebErrors errors = validate(checkcode, ext.getStoreName(),request, response);
		if (errors.hasErrors()) {
			return FrontHelper.showError(errors, web, model, request);
		}
		//设计店铺域名前缀
		String domainPreFix=global.getDomainPrefix();
		bean=storeMng.register(bean,ext,txt,member.getId(),domainPreFix,web,categoryId,false);
		log.info("register store '{}'", ext.getStoreName());
		Role role=new Role();
		role.setWebsite(web);
		role.setStore(bean);
		role.setName("店铺超级管理员");
		role.setPriority(10);
		role.setSuper(true);
		role.setNoedit(true);
		roleMng.save(role,member);
		ShopFrontHelper.setCommonData(request, model, web);
		return FrontHelper.showSuccess("global.success", "index.jhtml", web, model, request);
	}
	
	//店铺注册协议
	@RequestMapping(value = "/storeTreaty.jspx")
	public String storeTreaty(HttpServletRequest request, ModelMap model) {
			Website web = SiteUtils.getWeb(request);
			model.addAttribute("global", SiteUtils.getWeb(request).getGlobal());
			ShopFrontHelper.setCommonData(request, model, web);
			return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,
					REGISTER_STORE_TREATY), request);
	}
	
	//检查店铺名是否唯一
	@RequestMapping(value="/storename_unique.jspx")
	public void checkStorename(HttpServletRequest request,
			HttpServletResponse response) {
		String name = RequestUtils.getQueryParam(request, "storeName");
		// 用户名为空，返回false。
		if (StringUtils.isBlank(name)) {
			ResponseUtils.renderJson(response, "false");
			return;
		}
		// 用户名存在，返回false。
		if (storeExtMng.storeNameExist(name)) {
			ResponseUtils.renderJson(response, "false");
			return;
		}
		ResponseUtils.renderJson(response, "true");
	}
	
//	//检查邮箱是否唯一
//	@RequestMapping(value="/email_unique.jspx")
//	public void checkEmail(HttpServletRequest request,
//			HttpServletResponse response) {
//		String email = RequestUtils.getQueryParam(request, "email");
//		// email为空，返回false。
//		if (StringUtils.isBlank(email)) {
//			ResponseUtils.renderJson(response, "false");
//			return;
//		}
//		// email存在，返回false。
//		if (userMng.emailExist(email)) {
//			ResponseUtils.renderJson(response, "false");
//			return;
//		} 
//		ResponseUtils.renderJson(response, "true");
//	}
	
	private WebErrors validate(String checkcode, String name,HttpServletRequest request,
			HttpServletResponse response) {
		WebErrors errors = WebErrors.create(request);
		String id = session.getSessionId(request, response);
		if (errors.ifOutOfLength(checkcode, "checkcode", 3, 10)) {
			return errors;
		}
		try {
			if (!captchaService.validateResponseForID(id, checkcode
					.toUpperCase(Locale.ENGLISH))) {
				errors.addErrorCode("error.checkcodeIncorrect");
				return errors;
			}
		} catch (CaptchaServiceException e) {
			errors.addErrorCode("error.checkcodeInvalid");
			errors.addErrorString(e.getMessage());
			return errors;
		}
		if (errors.ifNotStorename(name, "name", 3, 100)) {
			return errors;
		}
		if (storeExtMng.storeNameExist(name)) {
			errors.addErrorCode("error.storenameExist");
			return errors;
		}
		return errors;
	}
	@Autowired
	private RoleMng roleMng;
	@Autowired
	private StoreMng storeMng;
	@Autowired
	private StoreExtMng storeExtMng;
	@Autowired
	private CategoryMng categoryMng;
	@Autowired
	private SessionProvider session;
	@Autowired
	private CaptchaService captchaService;
	@Autowired
	private ProductMng productMng;
	@Autowired
	private OrderMng orderMng;
}
